
import logging
import pandas as pd
import os
from flask import Flask, jsonify
from flask import request

app = Flask(__name__)
file = "./database/yian.xlsx"

print(file+"是否存在：%s" % os.path.exists(file))
print("current dir: %s" % os.path.abspath("."))

df = pd.read_excel(file, engine="openpyxl")
print(df.head(1))

basic_file = "./database/basic.xlsx"
df_zhongyao=pd.read_excel(basic_file, sheet_name="zhongyao", engine="openpyxl")
df_fangji=pd.read_excel(basic_file,sheet_name="fangji", engine="openpyxl")
df_xuewei=pd.read_excel(basic_file,sheet_name="xuewei", engine="openpyxl")
df_guji=pd.read_excel(basic_file,sheet_name="guji", engine="openpyxl")
df_zhi=pd.read_excel(basic_file,sheet_name="zhifa", engine="openpyxl")
df_mai=pd.read_excel(basic_file,sheet_name="mai", engine="openpyxl")
df_xiyi=pd.read_excel(basic_file,sheet_name="xiyi", engine="openpyxl")
df_zheng=pd.read_excel(basic_file,sheet_name="zheng", engine="openpyxl")
df_doctor=pd.read_excel(basic_file,sheet_name="doctor", engine="openpyxl")

@app.route('/yians', methods=['GET'])
def yian_list():
    result = {
        "yians":[],
        "zhongyaos":[],
        "fangjis":[],
        "xueweis":[],
        "gujis":[],
        "zhis":[],
        "mais":[],
        "xiyis":[],
        "zhengs":[],
        "doctors":[],
        "ret": 0,
        "total":0
    }
    try:
        # 1.分词  2.文本匹配 3.数据返回
        keyword = request.args["keyword"]
        type = request.args["type"]
        print("keyword:"+keyword+" type:"+type)
        keywords = keyword.split(" ")
        searchKeyRegex = ""
        for key in keywords:
            cat_key = "(?=.*"+key+")"
            if(searchKeyRegex == ""):
                searchKeyRegex = cat_key
                continue
            searchKeyRegex = cat_key+searchKeyRegex
        # (?=.*台积)(?=.*量产)^.*
        searchKeyRegex = searchKeyRegex + "^.*"
        print("searchKeyRegex:" + searchKeyRegex)
        # todo 可以优化为tag匹配，加快匹配速度
        yians = df[df['content'].str.contains(searchKeyRegex, regex=True)]
        zhongyaos = df_zhongyao[df_zhongyao['content'].str.contains(searchKeyRegex,regex=True)]
        fangjis = df_fangji[df_fangji['content'].str.contains(searchKeyRegex,regex=True)]
        xueweis = df_xuewei[df_xuewei['content'].str.contains(searchKeyRegex,regex=True)]
        gujis = df_guji[df_guji['content'].str.contains(searchKeyRegex,regex=True)]
        zhis = df_zhi[df_zhi['content'].str.contains(searchKeyRegex,regex=True)]
        mais = df_mai[df_mai['content'].str.contains(searchKeyRegex,regex=True)]
        xiyis = df_xiyi[df_xiyi['content'].str.contains(searchKeyRegex,regex=True)]
        zhengs = df_zheng[df_zheng['content'].str.contains(searchKeyRegex,regex=True)]
        doctors = df_doctor[df_doctor['content'].str.contains(searchKeyRegex,regex=True)]

        total = len(yians.index)
        result = {
            "yians":yians.to_dict("records"),
            "zhongyaos":zhongyaos.to_dict("records"),
            "fangjis":fangjis.to_dict("records"),
            "xueweis":xueweis.to_dict("records"),
            "gujis":gujis.to_dict('records'),
            "zhis":zhis.to_dict('records'),
            "mais":mais.to_dict('records'),
            "xiyis":xiyis.to_dict('records'),
            "zhengs":zhengs.to_dict('records'),
            "doctors":doctors.to_dict('records'),
            "ret": 1 if total>1 else 0,
            "total":total
        }
        print("返回结果数量：%s" % result['total'])
    except Exception as e:
        print ("error %s" % repr(e))
        logging.exception(e)
    # 需要转换为json对象
    return jsonify(result)

if __name__ == '__main__':
    # 需要使用0.0.0.0才能对外公网ip监听，否则默认的是127.0.0.1
    app.run(host='0.0.0.0', port=5000)
